import React, { useState } from 'react';
import { Modal, Form, Input, Row, Col, Upload, message } from 'antd';
import styles from './Application.less';

const FormItem = Form.Item;

const ApplicationModal = (props) => {

  const { applicationModalVisible, applicationRecord, operateType, onSave, updateDepartment, onCancel } = props;
  const [form] = Form.useForm();
  const { getFieldsValue, validateFields, setFieldsValue, resetFields } = form;
  const [ appIcon, setAppIcon ] = useState(null);

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  }

  const onOk = () => {
    validateFields().then(values => {
      appIcon ? values.icon = appIcon : "";
      operateType == "add" ? onSave(values) : updateDepartment(values);
    }).catch(error => {
      const errors = error.errorFields;
      for (let i = 0; i < errors.length; i++) {
        console.log(errors[i].name[0] + " ===>>> " + errors[i].errors[0]);
      }
    });
  }

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  const handleChange = (info) => {
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (url) => {
        setAppIcon(url);
        console.log("ApplicationModal handleChange getBase64 url => ", url);
      });
    }
  };

  return (
    <div>
      <Modal
        centered={true}
        visible={applicationModalVisible}
        title={operateType == "add" ? "新增" : "修改"}
        okText="保存"
        cancelText="取消"
        onCancel={onCancel}
        onOk={onOk}
        width={550}
        destroyOnClose={true}
        bodyStyle={{height: "320px"}}
      >
        <Form initialValues={applicationRecord} form={form} style={{marginLeft: "0px"}}>
          <Row>
            <Col span={0}>
              <FormItem label="应用ID" name={"id"}><Input /></FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem { ...formItemLayout } label="应用名称" name={"name"} rules={[{required: true, message: '请输入应用名称'}]}>
                <Input placeholder={"请输入应用名称"} />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem { ...formItemLayout } label="应用地址" name={"url"} rules={[{required: true, message: '请输入应用地址'}]}>
                <Input placeholder={"请输入应用地址"} />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem { ...formItemLayout } label="职责描述" name={"describe"} rules={[{required: true, message: '请输入职责描述'}]}>
                <Input.TextArea placeholder={"请输入职责描述"} />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <FormItem { ...formItemLayout } label="应用图标" name={"icon"} rules={[{required: true, message: '请输入应用图标'}]}>
                <div className={styles.app_icon}>
                  <Upload
                    name="icon"
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                  >
                    {
                      "edit" == operateType || appIcon ?
                        <img src={appIcon || applicationRecord?.icon} style={{ width: '100px', height: "100px" }} /> :
                        <button style={{ border: 0, background: 'none' }} type="button">
                          <div style={{ fontSize: 30 }}>+</div>
                        </button>
                    }
                  </Upload>
                </div>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
}

export default ApplicationModal;
